package br.edu.univas.si.es.correios.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.xml.KXml2DomDriver;

public class CorreioWebService implements BaseCorreioWebService {
	
	public WebServiceCep getCep(String CEP) throws IOException, JAXBException, StreamException{
		String urlString = "http://cep.republicavirtual.com.br/web_cep.php?cep="+CEP+"+&formato=xml";
			
		URL url = new URL(urlString);
		XStream xstream = new XStream(new KXml2DomDriver());
		xstream.alias("webservicecep", WebServiceCep.class);
		WebServiceCep wsc = (WebServiceCep)xstream.fromXML(url);
		return wsc;  
	
	}
	
	public String[] calculaFrete(int codServico, String cepOrigem, String cepDestino, String peso, String altura, String largura, String comprimento, String valorDeclarado)
	{
		String[] data = {"","",""};
		/*
	    calculaFrete("41106","26255170","96825150","0.1",null,null,null,null);
	    calculaFrete("40010","26255170","96825150","0.1",null,null,null,null);
		 */
		
		String modoEnvio = getServiceCodeByIndex(codServico);
		
		if(altura == null)
			altura="5";
		if(largura == null)
			largura="15";
		if(comprimento == null)
			comprimento="20";
		if(valorDeclarado == null)
			valorDeclarado="200";
	    
		String urlString = 
				"http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?" +
				"nCdEmpresa=" +
				"&sDsSenha=" +
				"&sCepOrigem="+cepOrigem+
				"&sCepDestino="+cepDestino+
				"&nVlPeso="+peso+
				"&nCdFormato=1" +
				"&nVlComprimento="+comprimento+
				"&nVlAltura="+altura+
				"&nVlLargura="+largura+
				"&sCdMaoPropria=s" +
				"&nVlValorDeclarado="+valorDeclarado+
				"&sCdAvisoRecebimento=n&nCdServico="+modoEnvio+
				"&nVlDiametro=0" +
				"&StrRetorno=xml";
	
		return requestFrete(data, urlString);
	  
	}
	private String[] requestFrete(String[] data, String urlString) {
		URL url;
		try {
			url = new URL(urlString);
			HttpURLConnection connection;
			try {
				connection = (HttpURLConnection) url.openConnection();
				connection.setRequestProperty("Request-Method", "GET");  
				connection.setDoInput(true);  
				connection.setDoOutput(false);  
				try {
					connection.connect();
					BufferedReader br =  
						    new BufferedReader(new InputStreamReader(connection.getInputStream()));  
					StringBuffer newData = new StringBuffer(10000);  
					String s = "";  
					while (null != ((s = br.readLine()))) {  
					    newData.append(s);  
					}  
					br.close();  
					String xml = new String(newData);
					
					 data[0] = "OK";
					 data[1] = xml.replaceFirst(".+<Valor>(.+)</Valor>.+", "$1");
					 data[2] = xml.replaceFirst(".+<PrazoEntrega>(.+)</PrazoEntrega>.+", "$1");
					return data;

				} catch (IOException e) {
					 data[0] = "ERROR";
					e.printStackTrace();
				}  
			} catch (IOException e1) {
				data[0] = "ERROR";
				e1.printStackTrace();
			}  
		} catch (MalformedURLException e) {
			data[0] = "ERROR";
			e.printStackTrace();
		} 
		 
		 return data;
	}
	
	private String getServiceCodeByIndex(int codServico) {
		String modoEnvio = PAC_TYPE_SERVICE;;
		switch (codServico) {
		case 2:
			modoEnvio = SEDEX_TYPE_SERVICE;
			break;
		case 3:
			modoEnvio = SEDEXCOBRAR_TYPE_SERVICE;
			break;
		case 4:
			modoEnvio = SEDEX10_TYPE_SERVICE;
			break;

		default:
			modoEnvio = PAC_TYPE_SERVICE;
			break;
		}
		return modoEnvio;
	}

}
